<template>
  <div>
    <div v-if="isCodeEdit">
      <textarea :value="content" @input="textAreaChanged" class="text-area-editor" style="border: solid 1px #bdbdbd;padding: 0.5rem"></textarea>
    </div>
    <div v-else>
      <quill-editor ref="htmlEditor" :value="content" :options="editorOptions" @input="quillChanged"></quill-editor>
    </div>
  </div>
</template>

<script>
import {setFontSize} from "./extension";
import {isEmpty} from "../../js/commonUtils";

import Quill from 'quill';

import htmlEditButton from "quill-html-edit-button";
Quill.register("modules/htmlEditButton", htmlEditButton);

import ImageResize from "quill-image-resize-module";
Quill.register('modules/imageResize', ImageResize);

let Align = Quill.import('attributors/style/align');
Quill.register(Align, true);

let Font = Quill.import('attributors/style/font');
Quill.register(Font, true);

let Size = Quill.import('attributors/style/size');
Quill.register(Size, true);

export default {
  name: "RichText",
  props: {
    isCodeEdit: {type: Boolean, default: false},
    options: {type: Object, default: null},
    content: {type: String, default: "", required: true},
    imageHandler:  {type: Function},
  },
  model: {
    prop: "content",
    event: "change"
  },
  data() {
    return {
      editorOptions: {
        placeholder: '请编辑页面内容',
        modules: {
          imageResize: {
            displayStyles: {
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: ["Resize", "DisplaySize", "Toolbar"]
          },
          toolbar: {
            container: [
              // [{'font': []}],//字体
              [{'header': [1, 2, 3, 4, 5, false]}, {'size': ['small', false, 'large', 'huge']}],//几级标题
              ['bold', 'italic', 'underline', 'strike'],//加粗，斜体，下划线，删除线
              ['blockquote', 'link'],//引用，代码块
              [{'list': 'ordered'}, {'list': 'bullet'}],//列表
              [{'color': []}, {'background': []}],// 字体颜色，字体背景颜色
              [{'align': []}],//对齐方式
              ['image', 'video'],//上传图片、上传视频,
              ['clean'],//清除字体样式
            ],
            handlers: {
              image: this.selectImage,
              size: this.setFontSize,
            }
          },
          htmlEditButton: {}
        }
      },
    }
  },
  methods: {
    isEmpty(val) {
      return isEmpty(val);
    },
    selectImage() {
      if(this.imageHandler) {
        this.imageHandler(this, "htmlEditor");
      }
    },
    setFontSize(value) {
      setFontSize(this, "htmlEditor", value);
    },
    textAreaChanged(e) {
      this.$emit("change", e.target.value);
    },
    quillChanged(text) {
      this.$emit("change", text);
    },
  },
}
</script>

<style scoped lang="less">
@import "~quill/dist/quill.core.css";
@import "~quill/dist/quill.snow.css";

.text-area-editor {
  width: 100%;
  height: 340px;
}
.quill-editor {
  height: 300px;
  margin-bottom: 50px;
}
</style>
